package com.hernie.piggymall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.hernie.common.utils.R;
import com.hernie.piggymall.product.entity.SkuImagesEntity;
import com.hernie.piggymall.product.entity.SpuInfoDescEntity;
import com.hernie.piggymall.product.feign.SeckillFeignService;
import com.hernie.piggymall.product.service.*;
import com.hernie.piggymall.product.vo.SeckillInfoVo;
import com.hernie.piggymall.product.vo.SkuItemSaleAttrVo;
import com.hernie.piggymall.product.vo.SkuItemVo;
import com.hernie.piggymall.product.vo.SpuItemAttrGroupVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hernie.common.utils.PageUtils;
import com.hernie.common.utils.Query;

import com.hernie.piggymall.product.dao.SkuInfoDao;
import com.hernie.piggymall.product.entity.SkuInfoEntity;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private AttrGroupService attrGroupService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private ThreadPoolExecutor executor;
    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        this.baseMapper.insert(skuInfoEntity);
    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        LambdaQueryWrapper<SkuInfoEntity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank((String) params.get("key"))) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq(SkuInfoEntity::getSkuId, params.get("key")).or().like(SkuInfoEntity::getSkuName, params.get("key"));
            });
        }
        if (StringUtils.isNotBlank((String) params.get("catelogId")) && !"0".equalsIgnoreCase((String) params.get("catelogId"))) {
            queryWrapper.eq(SkuInfoEntity::getBrandId, params.get("catelogId"));
        }
        if (StringUtils.isNotBlank((String) params.get("brandId")) && !"0".equalsIgnoreCase((String) params.get("brandId"))) {
            queryWrapper.eq(SkuInfoEntity::getBrandId, params.get("brandId"));
        }
        if (StringUtils.isNotBlank((String) params.get("min"))) {
            queryWrapper.ge(SkuInfoEntity::getPrice, params.get("min")); // 大于等于
        }
        if (StringUtils.isNotBlank((String) params.get("max"))) {
            try{
                BigDecimal bigDecimal = new BigDecimal((String) params.get("max"));

                if(bigDecimal.compareTo(new BigDecimal("0"))==1){
                    queryWrapper.le(SkuInfoEntity::getPrice, params.get("max")); // 小于等于
                }
            }catch (Exception e){

            }
        }
        IPage<SkuInfoEntity> page = this.page(
                new Query<SkuInfoEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    public List<SkuInfoEntity> getSkusBySpuId(Long spuId) {
        List<SkuInfoEntity> list = this.list(new LambdaQueryWrapper<SkuInfoEntity>().eq(SkuInfoEntity::getSpuId, spuId));
        return list;
    }

    @Override
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            // sku 基本信息获取 pms_sku_info
            SkuInfoEntity skuInfoEntity = this.baseMapper.selectById(skuId);
            skuItemVo.setInfo(skuInfoEntity);
            return skuInfoEntity;
        }, executor);

        CompletableFuture<Void> spuAttrFuture = skuInfoFuture.thenAcceptAsync(res -> {
            // 获取spu的销售属性组合
            List<SkuItemSaleAttrVo> skuItemSaleAttrVos = skuSaleAttrValueService.getSaleAttrBySpuId(res.getSpuId());
            skuItemVo.setSaleAttr(skuItemSaleAttrVos);
        }, executor);

        CompletableFuture<Void> spuDescFuture = skuInfoFuture.thenAcceptAsync(res -> {
            // 获取spu的介绍 pms_spu_info_desc
            SpuInfoDescEntity spuInfoDescEntity = spuInfoDescService.getById(res.getSpuId());
            skuItemVo.setDesc(spuInfoDescEntity);
        }, executor);

        CompletableFuture<Void> spuBaseAttrFuture = skuInfoFuture.thenAcceptAsync(res -> {
            // 获取spu的规格参数信息
            List<SpuItemAttrGroupVo> attrGroupVos = attrGroupService.getAttrGroupWithAttrsBySpuId(res.getSpuId(), res.getCatalogId());
            skuItemVo.setGroupAttrs(attrGroupVos);
        }, executor);

        CompletableFuture<Void> skuImagesFuture = CompletableFuture.runAsync(() -> {
            // sku 图片信息 pms_sku_images
            List<SkuImagesEntity> skuImagesEntities = skuImagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(skuImagesEntities);
        }, executor);

        // 查询当前sku是否参与秒杀优惠
        CompletableFuture<Void> secKillFutere = CompletableFuture.runAsync(() -> {
            R r = seckillFeignService.getSkuSeckillInfo(skuId);
            if (r.getCode() == 0) {
                SeckillInfoVo seckillInfoVo = r.getData(new TypeReference<SeckillInfoVo>() {
                });
                skuItemVo.setSeckillInfo(seckillInfoVo);
            }
        }, executor);


        // 等所有任务都完成
        CompletableFuture.allOf(spuAttrFuture, spuDescFuture, spuBaseAttrFuture, skuImagesFuture, secKillFutere).get();

        return skuItemVo;
    }

}